<template>
  <div>
    <!-- 主要内容输入框和搜索重置按钮 -->
    <i-search ref="iSearch" :model="formData" @search="fetch" @reset="reset">
      <el-form-item label="司机编号" prop="driverId">
        <el-input v-model="formData.driverId"></el-input>
      </el-form-item>
      <el-form-item label="司机姓名" prop="driverName">
        <el-input v-model="formData.driverName"></el-input>
      </el-form-item>
      <el-form-item label="所在省份" prop="province">
        <el-select
          v-model="formData.province"
          placeholder="请选择"
          class="selectlocation"
          @change="showMessage($event)"
        >
          <el-option
            v-for="(item,index) in ProvinceData"
            :label="item.dictoryValue"
            :value="item.dictoryId"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所在城市" prop="city">
        <el-select
          v-model="formData.city"
          placeholder="请选择"
          class="selectlocation"
          @change="showCityMessage($event)"
        >
          <el-option
            v-for="(item,index) in CityData"
            :label="item.dictoryValue"
            :value="item.dictoryId"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所在区" prop="district">
        <el-select v-model="formData.district" placeholder="请选择" class="selectlocation">
          <el-option
            v-for="(item,index) in areaData"
            :label="item.dictoryValue"
            :value="item.dictoryId"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
    </i-search>

    <!-- 表格区域 -->
    <i-table
      :toolbar="toolbar"
      :tableData="tableData"
      :pageInfo="pageInfo"
      :selectionShow="true"
      @handleCurrentChange="handleCurrentChange"
      @handleSizeChange="handleSizeChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        v-for="(item,index) in columnList"
        :key="index"
        :label="item.label"
        :prop="item.prop"
        align="center"
      ></el-table-column>
    </i-table>
    <!-- 点击新增按钮后的弹出框 -->
    <i-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      @dialog-before-close="dialogBeforeClose"
      @dialog-cancel="dialogCancel"
      @dialog-confirm="dialogConfirm"
    >
      <el-form
        :model="dialogFormData"
        ref="formRef"
        :rules="formRules"
        label-width="100px"
        label="新增门店"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="司机姓名" prop="driverName">
              <el-input v-model="dialogFormData.driverName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="driverPhone">
              <el-input v-model="dialogFormData.driverPhone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="司机账号" prop="userAccount">
              <el-input v-model="dialogFormData.userAccount"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="dialogFormData.password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="司机性别" prop="driverSex">
              <el-select v-model="dialogFormData.driverSex" placeholder="请选择">
                <el-option label="男" value="0"></el-option>
                <el-option label="女" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="司机邮箱" prop="driverEmail">
              <el-input v-model="dialogFormData.driverEmail"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="driverIdCard">
              <el-input v-model="dialogFormData.driverIdCard"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在省份" prop="province">
              <el-select
                v-model="dialogFormData.province"
                placeholder="请选择"
                class="selectlocation"
                @change="showMessage($event)"
              >
                <el-option
                  v-for="(item,index) in ProvinceData"
                  :label="item.dictoryValue"
                  :value="item.dictoryId"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所在城市" prop="city">
              <el-select
                v-model="dialogFormData.city"
                placeholder="请选择"
                class="selectlocation"
                @change="showCityMessage($event)"
              >
                <el-option
                  v-for="(item,index) in CityData"
                  :label="item.dictoryValue"
                  :value="item.dictoryId"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在区" prop="district">
              <el-select v-model="dialogFormData.district" placeholder="请选择" class="selectlocation">
                <el-option
                  v-for="(item,index) in areaData"
                  :label="item.dictoryValue"
                  :value="item.dictoryId"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传头像" prop="picturePath">
              <div class="btn-box">
                点击上传
                <input type="file" id="addfile" @change="inputChange($event)" />
              </div>
              <div class="imginfourl">{{this.dialogFormData.picturePath}}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </i-dialog>
    <!-- 司机详情 -->
    <el-dialog
      title="司机详情"
      :visible.sync="shopDetaildialogVisible"
      width="70%"
      :before-close="handleClose"
    >
      <!-- 门店详情表格区域 -->
      <el-table :data="detailTableDate" border style="width: 100%">
        <el-table-column
          v-for="(item,index) in detailcolumnList"
          :key="index"
          :label="item.label"
          :prop="item.prop"
          align="center"
        ></el-table-column>
      </el-table>
      <span slot="footer">
        <el-button @click="shopDetaildialogVisibled">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 修改司机会话框 -->
    <i-dialog
      v-model="editdialogVisible"
      :title="editdialogTitle"
      @dialog-before-close="editdialogBeforeClose"
      @dialog-cancel="editdialogCancel"
      @dialog-confirm="editdialogConfirm"
    >
      <el-form
        :model="editdialogFormData"
        ref="editformRef"
        :rules="editformRules"
        label-width="100px"
        label="修改门店"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="司机账号" prop="userAccount">
              <el-input v-model="editdialogFormData.userAccount" disabled></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="editdialogFormData.password"></el-input>
            </el-form-item>
          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="司机姓名" prop="driverName">
              <el-input v-model="editdialogFormData.driverName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="driverPhone">
              <el-input v-model="editdialogFormData.driverPhone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="司机性别" prop="driverSex">
              <el-select v-model="editdialogFormData.driverSex" placeholder="请选择">
                <el-option label="男" value="0"></el-option>
                <el-option label="女" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="司机邮箱" prop="driverEmail">
              <el-input v-model="editdialogFormData.driverEmail"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="driverIdCard">
              <el-input v-model="editdialogFormData.driverIdCard"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在省份" prop="province">
              <el-select
                v-model="editdialogFormData.province"
                placeholder="请选择"
                class="selectlocation"
                @change="showMessage($event)"
              >
                <el-option
                  v-for="(item,index) in ProvinceData"
                  :label="item.dictoryValue"
                  :value="item.dictoryId"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所在城市" prop="city">
              <el-select
                v-model="editdialogFormData.city"
                placeholder="请选择"
                class="selectlocation"
                @change="showCityMessage($event)"
              >
                <el-option
                  v-for="(item,index) in CityData"
                  :label="item.dictoryValue"
                  :value="item.dictoryId"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在区" prop="district">
              <el-select
                v-model="editdialogFormData.district"
                placeholder="请选择"
                class="selectlocation"
              >
                <el-option
                  v-for="(item,index) in areaData"
                  :label="item.dictoryValue"
                  :value="item.dictoryId"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传头像" prop="picturePath">
              <div class="btn-box">
                点击上传
                <input type="file" id="editfile" @change="editinputChange($event)" />
              </div>
              <div class="imginfourl">{{this.editdialogFormData.picturePath}}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </i-dialog>
  </div>
</template>

<script>
// 注意首两个字母要大写，这样才会被识别出来所调用的子组件
import ISearch from "../../components/common/i-search.vue";
import ITable from "../../components/common/i-table.vue";
import IDialog from "../../components/common/i-dialog.vue";
import req from "@/api/driver-info-manage.js";
import axios from "axios";
export default {
  name: "driver-info-manage",
  data() {
     // 自定义验证身份证
    var validateIdCard = (rule, value, callback) => {
      let regIdcard = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/

      console.log('te', regIdcard.test(value))

      if (regIdcard.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入正确的身份证号'))
        this.$message.info('请输入正确的身份证号码')
      }
    }
    return {
      // 搜索框数据对象
      formData: {
        driverId: "",
        driverName: ""
      },
      // 新增按钮弹出框输入的数据对象
      dialogFormData: {
        driverName: "",
        driverPhone: "",
        userAccount: "",
        password: "",
        driverEmail: "",
        picturePath: ""
      },
      // 修改司机会话框数据
      editdialogFormData: {},
      // 设置新增弹出框的默认状态为隐藏
      dialogVisible: false,
      // 司机详情会话框默认为隐藏
      shopDetaildialogVisible: false,
      // 设置修改会话框默认状态为隐藏
      editdialogVisible: false,
      // 存储选中司机 信息的id
      multipId: [],
      // 新增按钮的弹出框标题提示
      dialogTitle: "新增司机",
      // 修改按钮会话框标题
      editdialogTitle: "修改司机信息",
      // 存放所有的省市区数据
      ProvinceData: [],
      CityData: [],
      areaData: [],
      // 选择省市对应的id
      provinceId: "",
      cityId: "",
      // 店长详情数组
      detailTableDate: [],
      // 店长详情对象
      detailTableDateArr: {},
      // 分页数据
      pageInfo: {
        pageIndex: 1,
        pageSize: 5,
        total: 0
      },
      // 表格区域多个按钮数据设置
      toolbar: [
        {
          btnName: "详情",
          type: "primary",
          // 设置按钮的触发事件
          func: () => {
            // console.log(this.multipId);
            if (this.multipId.length === 1) {
              this.shopDetaildialogVisible = true;
              req("getDriverDetail", {
                driverId: this.multipId[0]
              }).then(data => {
                // if(data.data.driverSex)
                // 把返回的数据对象转化为数组来进行查询显示
                this.detailTableDateArr = data.data;
                if (this.detailTableDateArr.driverSex === '1') {
            this.detailTableDateArr.driverSex = "女";
          } else if (this.detailTableDateArr.driverSex === '0') {
            this.detailTableDateArr.driverSex = "男";
          }
                this.detailTableDate.push(this.detailTableDateArr);

// 清空id
                this.multipId = [];
                console.log(typeof this.detailTableDate[0].driverSex)
              });
            }
          }
        },
        {
          btnName: "新增",
          type: "primary",
          // 设置按钮的触发事件
          func: () => {
            this.dialogVisible = true;
          }
        },
        {
          btnName: "修改",
          type: "primary",
          func: () => {
            if (this.multipId.length === 1) {
              this.editdialogVisible = true;
              req("getDriver", {
                driverId: this.multipId[0]
              }).then(data => {
                console.log(data);
                this.getlistCity(data.data.province);
                this.getlistDistrict(data.data.city);
                this.editdialogFormData = data.data;
              });
            } 
            // else {
            //   this.$message.error("请选择单个司机进行修改！");
            //   // this.reload();
            // }
          }
        },
        {
          btnName: "删除",
          type: "primary",
          func: async () => {
            if (this.multipId.length !== 0) {
              const confirmResult = await this.$confirm(
                "此操作将永久删除所选司机, 是否继续?",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                }
              ).catch(err => err);
              if (confirmResult !== "confirm") {
                 this.$message("已取消删除");
                this.fetch();
              } else {
                req("deleteDriver", {
                  driverId: this.multipId.join(",")
                }).then(data => {
                  if (data.code !== 0) {
                    return this.$message.error("删除门店失败");
                  }
                  this.$message.success("删除门店成功");
                  // this.reload();
                  this.fetch()
                });
              }
            }
          }
        }
      ],
      // 表格表头数据
      columnList: [
        { label: "司机编号", prop: "driverId" },
        { label: "姓名", prop: "driverName" },
        { label: "手机", prop: "driverPhone" },
        { label: "身份证", prop: "driverIdCard" },
        { label: "邮箱", prop: "driverEmail" },
        { label: "性别", prop: "driverSex" }
      ],
      detailcolumnList: [
        { label: "司机编号", prop: "driverId" },
        { label: "身份证", prop: "driverIdCard" },
        { label: "姓名", prop: "driverName" },
        { label: "司机用户电话", prop: "driverPhone" },
        { label: "省市区地址", prop: "area" },
        { label: "用户账号", prop: "userAccount" },
        { label: "司机性别", prop: "driverSex" }
      ],
      // 表格内容数据
      tableData: [],
      // 表单验证规则
      formRules: {
        driverName: [
          { required: true, message: "请输入司机姓名", trigger: "change" }
        ],
        driverPhone: [
          { required: true, message: "请输入联系电话", trigger: "change" }
        ],
        userAccount: [
          { required: true, message: "请输入司机账号", trigger: "change" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" }
        ],
        driverSex: [
          { required: true, message: "请选择性别", trigger: "change" }
        ],
        driverEmail: [
          { required: true, message: "请输入邮箱", trigger: "change" }
        ],
        driverIdCard: [
          { required: true, message: "请输入身份证号", trigger: "change" },
          { validator: validateIdCard, trigger: 'blur' }
        ],
        province: [
          { required: true, message: "请选择所在省份", trigger: "change" }
        ],
        city: [
          { required: true, message: "请选择所在城市", trigger: "change" }
        ],
        district: [
          { required: true, message: "请选择所在区", trigger: "change" }
        ]
      },
      editformRules: {
        driverName: [
          { required: true, message: "请输入司机姓名", trigger: "change" }
        ],
        driverPhone: [
          { required: true, message: "请输入联系电话", trigger: "change" }
        ],
        userAccount: [
          { required: true, message: "请输入司机账号", trigger: "change" }
        ],
        driverSex: [
          { required: true, message: "请选择性别", trigger: "change" }
        ],
        driverEmail: [
          { required: true, message: "请输入邮箱", trigger: "change" }
        ],
        driverIdCard: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
          { validator: validateIdCard, trigger: 'blur' }
        ],
        province: [
          { required: true, message: "请选择所在省份", trigger: "change" }
        ],
        city: [
          { required: true, message: "请选择所在城市", trigger: "change" }
        ],
        district: [
          { required: true, message: "请选择所在区", trigger: "change" }
        ]
      }
    };
  },
  mounted() {
    this.fetch(), this.getProvince();
  },
  methods: {
    // 新增会话框图片上传
    inputChange(event) {
      let form = new FormData();
      let file = document.getElementById("addfile").files[0];

      form.append("multipartFile", file, file.name);
      axios({
        method: "post",
        url: "http://120.76.142.108:8080/pc/image/upload",
        data: form,
        headers: {
          "Content-Type": "Multipart/form-data"
        }
      }).then(data => {
        console.log("data", data);
        if(data.data.code === 0){
this.dialogFormData.picturePath = data.data.data;
         this.$notify({
          title: '成功',
          message:data.data.msg,
          type: 'success'
        });
        }else{
          this.$notify({
          title: '失败',
          message:data.data.msg,
          type: 'warning'
        });
        }
        
      });
    },
    editinputChange(event) {
      let form = new FormData();
      let file = document.getElementById("editfile").files[0];

      form.append("multipartFile", file, file.name);
      axios({
        method: "post",
        url: "http://120.76.142.108:8080/pc/image/upload",
        data: form,
        headers: {
          "Content-Type": "Multipart/form-data"
        }
      }).then(data => {
        console.log("data", data);
        if(data.data.code === 0){
this.editdialogFormData.picturePath = data.data.data;
         this.$notify({
          title: '成功',
          message:'图片修改成功',
          type: 'success'
        });
        }else{
          this.$notify({
          title: '失败',
          message:'图片修改失败',
          type: 'warning'
        });
        }
        
      });
    },
    // 获取选择的省的id
    showMessage(e) {
      this.provinceId = e;
      this.getlistCity();
    },
    // 获取选择的市的id
    showCityMessage(e) {
      this.cityId = e;
      this.getlistDistrict();
    },
    // 获取省会
    getProvince() {
      req("listProvince", {}).then(data => {
        this.ProvinceData = data.data;
      });
    },
    // 获取城市
    getlistCity(number) {
      if (number) {
        req("listCity", {
          parentId: number
        }).then(data => {
          console.log(data);
          // this.editdialogFormData.city
          this.CityData = data.data;
        });
      }
      req("listCity", {
        parentId: this.provinceId
      }).then(data => {
        // console.log(data);
        this.CityData = data.data;
      });
    },
    // 获取对应区
    getlistDistrict(number) {
      if (number) {
        req("listDistrict", {
          parentId: number
        }).then(data => {
          // console.log(data);
          this.areaData = data.data;
        });
      }
      req("listDistrict", {
        parentId: this.cityId
      }).then(data => {
        // console.log(data);
        this.areaData = data.data;
      });
    },
    fetch() {
      this.pageInfo.pageIndex = 1;
      this.pageInfo.pageSize = 5;
      this.search();
    },
    search() {
      req("getTableData", {
        // access_token: JSON.parse(sessionStorage.getItem("userInfo"))
        //   .access_token,
        ...this.formData,
        role: JSON.parse(sessionStorage.getItem("role")).role,
        pageSize: this.pageInfo.pageSize,
        pageNum: this.pageInfo.pageIndex
      }).then(data => {
        console.log(data);
        this.pageInfo.total = data.data.total;
        this.pageInfo.pageSize = data.data.pageSize;
        this.pageInfo.pageIndex = data.data.pageNum;
        this.tableData = data.data.list;

        // 把返回的性别信息替换成对应性别
        this.tableData.forEach(item => {
          if (item.driverSex === 1) {
            item.driverSex = "女";
          } else if (item.driverSex === 0) {
            item.driverSex = "男";
          }
        });
      });
    },
    reset() {
      // this.reload()
      this.fetch();
    },
    // 每页多少条数据
    handleSizeChange(value) {
      console.log(value);
      this.pageInfo.pageSize = value;
      this.search();
    },
    // 当前页
    handleCurrentChange(value) {
      console.log(value);
      this.pageInfo.pageIndex = value;
      this.search();
    },
    handleSelectionChange(rows) {
      console.log(rows);
      this.multipId = [];
      rows.forEach(item => {
        this.multipId.push(item.driverId);
      });
    },
    // 点击取消隐藏弹出的表单
    dialogCancel() {
      this.dialogVisible = false;
      this.$refs.formRef.resetFields();
      this.fetch();
    },
    // 点击取消隐藏弹出的修改表单
    editdialogCancel() {
      this.editdialogVisible = false;
      this.$refs.editformRef.resetFields();
      this.fetch();
    },
    // 在表单关闭之前清空表单的数据
    dialogBeforeClose() {
      this.dialogVisible = false;
      this.$refs.formRef.resetFields();
      this.fetch();
    },
    // 在表单关闭之前清空修改表单的数据
    editdialogBeforeClose() {
      this.editdialogVisible = false;
      this.$refs.editformRef.resetFields();
      this.fetch();
    },

    // 新增点击表单确认按钮后事件
    dialogConfirm() {
      // 将性别转化为数字
      if (this.dialogFormData.driverSex) {
        this.dialogFormData.driverSex = parseInt(this.dialogFormData.driverSex);
        console.log(typeof this.dialogFormData.driverSex);
      } else {
        console.log("0");
      }
      this.$refs.formRef.validate(async valid => {
        if (!valid) return;
        req("addDriver", {
          ...this.dialogFormData
        }).then(data => {
          console.log(data);
          if (data.code !== 0) {
            return this.$message.error(data.msg);
          } else {
            this.$message.success(data.msg);
          }
          // 隐藏对话框
          this.dialogVisible = false;
          // 刷新页面
          // this.reload();
          this.fetch();
        });
      });
    },
    // 修改点击表单确认按钮后事件
    editdialogConfirm() {
      // 将性别转化为数字
      if (this.editdialogFormData.driverSex) {
        this.editdialogFormData.driverSex = parseInt(
          this.editdialogFormData.driverSex
        );
        console.log(typeof this.editdialogFormData.driverSex);
      } else {
        console.log("0");
      }
      this.$refs.editformRef.validate(async valid => {
        if (!valid) return;
        req("updateDriver", {
          ...this.editdialogFormData
        }).then(data => {
          console.log(data);
          if (data.code !== 0) {
            return this.$message.error(data.msg);
          } else {
            this.$message.success(data.msg);
          }
          // 隐藏对话框
          this.editdialogVisible = false;
          // 刷新页面
          // this.reload();
          this.fetch();
        });
      });
    },
    // 详情对话框关闭事件
    handleClose() {
      // this.reload();
      this.detailTableDateArr=[]
      this.detailTableDate=[]
      this.shopDetaildialogVisible = false;

      this.fetch();
    },
    shopDetaildialogVisibled() {
      // this.reload();
      this.detailTableDateArr=[]
      this.detailTableDate=[]
      this.shopDetaildialogVisible = false;
      this.fetch();
    }
  },
  // 子组件注册
  components: {
    ISearch,
    ITable,
    IDialog
  }
};
</script>

<style lang="scss" scoped>
// 地点选择框宽度控制
.selectlocation {
  width: 207px;
}
.el-input{
  width: 218px;
}
</style>
